package br.sed.theenemy.presentation.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import br.sed.theenemy.business.exception.DBException;
import br.sed.theenemy.business.services.Services;
import br.sed.theenemy.model.bean.User;
import br.sed.theenemy.presentation.EnemyConstants;
import br.sed.theenemy.presentation.UserSession;
import br.sed.theenemy.presentation.form.SearchForm;
import br.sed.theenemy.presentation.vo.UserVO;

/**
 * 
 * @author JulioCB
 * @email jcbjulio@gmail.com
 * 
 */
public class FindByNameAction extends DispatchAction {

	// forwards
    private final String SEARCH_PAGE = "SearchPage";
    
	public ActionForward unspecified(final ActionMapping mapping,
	           final ActionForm form, final HttpServletRequest request, 
	           final HttpServletResponse response) {
		SearchForm searchForm = (SearchForm) form;
		Services services = Services.getInstance();
		
		final UserSession session = new UserSession(request, false);
        final User userLogged = session.getLoggedUser();
        
        if (userLogged == null) {
            // User not logged in, setting flag
            searchForm.setUserLogged(false);
            return mapping.findForward(SEARCH_PAGE);
        }

        if(!form.validate(mapping, request).isEmpty()){
            searchForm.setInvalid(true);
            return mapping.findForward(SEARCH_PAGE);
        }
        
        String name = searchForm.getName();
        int page = searchForm.getPage();
        int max = searchForm.getMax();
        
        List<User> userList = null;
		try {
			 userList = services.findUserByPieceOfName(name, page, max);
		} catch (DBException e) {
		    return mapping.findForward(EnemyConstants.ERROR_PAGE);
		}
		
		List<UserVO> userListVO = new ArrayList<UserVO>();
		for (User user: userList){
			UserVO userVO = new UserVO(user);
			userListVO.add(userVO);
		}
        
		searchForm.setUser(userListVO);
		
        return mapping.findForward(SEARCH_PAGE);
	}
}
